package com.qfedu.config;

import com.qfedu.dao.PermissionRepository;
import com.qfedu.dao.UserRepository;
import com.qfedu.pojo.entity.User;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserRepository userRepository;

    @Autowired
    PermissionRepository permissionRepository;

    /**
     * 用户授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //1.获取后台页面传入的用户信息
        String userName = (String) principalCollection.getPrimaryPrincipal();
        //2.通过用户名去数据库中查询管理员所拥有的权限
        List<String> permissions = permissionRepository.selectPermissionByUserName(userName);
        //3.将查询到的权限集合交给shiro管理
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addStringPermissions(permissions);
        return simpleAuthorizationInfo;
//        return null;
    }

    /**
     * 用户认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //1.获取前端传入的参数
        String userName = (String) authenticationToken.getPrincipal();
        //2.通过用户名去数据库中查找用户的信息
        User user = userRepository.findByUserName(userName);
        //再将用户信息交给shiro之前先进性一次判断，保证用户不为空的情况下才可以放入shiro中去进行对比
        if(user != null) {
            //3.将用户名，正确的密码、盐值以及本类类名交给shiro进行管理
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(userName, user.getPassword(), ByteSource.Util.bytes(userName), this.getName());
            return simpleAuthenticationInfo;
        }
        return null;
    }
}
